<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width='1100'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <a-form
      layout='horizontal'
      ref='form'
      :model='form'
      :rules='rules'
      :label-col='{ md: { span: 4 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 20 }, sm: { span: 24 } }'
    >

      <!--基本信息 -->
      <div class="card-title card-title-background">基本信息</div>
      <a-form-item label='事件规则名称:' name='strategyName'>
        <a-input v-model:value='form.strategyName' placeholder='请输入事件规则名称' allow-clear autocomplete='off'/>
      </a-form-item>

      <a-form-item label='事件告警级别:' name='triggerLevel'>
        <a-select v-model:value="form.triggerLevel">
          <a-select-option :value="1">严重</a-select-option>
          <a-select-option :value="2">警告</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label='是否启用:' name='enableTrigger'>
        <a-select v-model:value="form.enableTrigger">
          <a-select-option :value="1">启用</a-select-option>
          <a-select-option :value="2">关闭</a-select-option>
        </a-select>
      </a-form-item>

      <!--告警对象 -->
      <div class="card-title card-title-background">事件源</div>
      <a-form-item label="所属事件源:" name="sourceId">
        <a-select
          show-search
          v-model:value="form.sourceId"
          placeholder="请选择所属事件源"
          style="width: 205px;"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          @change="handleSelectSourceChange"
        >
          <a-select-option v-for="item in sourceList" :key="item.sourceId" >
            {{ item.thirdName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <div>
      <MonitorsStrategyEventstrategySubRule v-for="(item, index) in objectRules"
                                  :key="index" :index="index" :rule="item" @deleteIndex="removeRule"
                                  :sourceEvents="sourceEvents"
      />
    </div>
    <a-space>
      <a-button type="primary" @click="addRule">
        <template #icon>
          <plus-outlined/>
        </template>
        <span>新增策略规则</span>
      </a-button>
    </a-space>
  </a-modal>
</template>

<script>
import { MonitorEventSubscribeStrategyApi } from '@/api/monitors/MonitorEventSubscribeStrategyApi';
import {MonitorEventSourceApi} from "@/api/monitors/MonitorEventSourceApi";
import { message } from 'ant-design-vue';
import MonitorsStrategyEventstrategySubRule from './eventstrategy-sub-rule.vue'
import {MonitorEventApi} from "@/api/monitors/MonitorEventApi";
export default {
  name: 'MonitorsStrategyEventstrategyEdit',
  components: {
    MonitorsStrategyEventstrategySubRule
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  created() {
    MonitorEventSourceApi.list({}).then(resp => {
      let _sourceList = (resp ? resp.data : null) || [];
      this.sourceList = _sourceList;
    });
    if (this.data) {
      let that = this;
      this.isUpdate = true;
      this.form = Object.assign({}, this.data);
      MonitorEventSubscribeStrategyApi.detail({"strategyId": this.data.strategyId}).then(result => {
        if (result.rules && result.rules.length > 0) {
          let objectRulesArr = [];
          for (let i = 0; i < result.rules.length; i++) {
            let objectRuleItem = {
              "eventId" : result.rules[i].eventId,
              "periodType" : result.rules[i].periodType,
              "periodValue" : result.rules[i].periodValue,
              "ruleId" : result.rules[i].ruleId,
              "strategyId" : result.rules[i].strategyId
            };
            objectRulesArr.push(objectRuleItem);
          }
          that.objectRules = objectRulesArr;
        }
        MonitorEventApi.list({"sourceId": result.sourceId}).then(result => {
          let optionArr = [], length = result.data.length || 0;
          if (result.data && length > 0) {
            for (let i = 0; i < length; i++) {
              optionArr.push({
                value: result.data[i].eventId,
                label: result.data[i].eventName,
              });
            }
          }
          that.sourceEvents = optionArr;
        }).catch((err) => {
          console.log(err)
        });
      });
    } else {
      this.form = {};
      this.isUpdate = false;
    }
    if (this.$refs.form) {
      this.$refs.form.clearValidate();
    }
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      objectRules: [{}],
      // 表单验证规则
      rules: {
        strategyName: [{ required: true, message: '请输入事件监控名称', type: 'string', trigger: 'blur' }],
        triggerLevel: [{ required: true, message: '请输入1 严重 2警告', type: 'number', trigger: 'blur' }],
        enableTrigger: [{ required: true, message: '请输入是否启用 1启用 2关闭', type: 'number', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      sourceList : [],
      sourceEvents : []
    };
  },
  methods: {
    /**
     * 保存和编辑
     *
     * @author cancan
     * @date 2024/12/15 16:16
     */
    async save() {
      console.log(this.form);
      // 校验表单
      await this.$refs.form.validate();
      if (this.form.sourceId == null) {
        message.error("请选择事件源");
        return;
      }
      if (this.objectRules == null || this.objectRules.length == 0) {
        message.error("请完善规格");
        return;
      }

      // 修改加载框为正在加载
      this.loading = true;
      let result = null;
      // 执行编辑或修改
      if (this.isUpdate) {
        let objectsFrom = {
          strategyName: this.form.strategyName,
          triggerLevel: this.form.triggerLevel,
          enableTrigger: this.form.enableTrigger,
          sourceId: this.form.sourceId,
          rules: this.objectRules,
          strategyId : this.form.strategyId
        };
        result = MonitorEventSubscribeStrategyApi.edit(objectsFrom);
      } else {
        let objectsFrom = {
          strategyName: this.form.strategyName,
          triggerLevel: this.form.triggerLevel,
          enableTrigger: this.form.enableTrigger,
          sourceId: this.form.sourceId,
          rules: this.objectRules
        };
        console.log(objectsFrom);
        result = MonitorEventSubscribeStrategyApi.add(objectsFrom);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author cancan
     * @date 2024/12/15 16:16
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    handleSelectSourceChange(sourceId) {
      let that = this;
      that.objectRules = [{}];
      MonitorEventApi.list({"sourceId": sourceId}).then(result => {
        let optionArr = [], length = result.data.length || 0;
        if (result.data && length > 0) {
          for (let i = 0; i < length; i++) {
            optionArr.push({
              value: result.data[i].eventId,
              label: result.data[i].eventName,
            });
          }
        }
        that.sourceEvents = optionArr;
        console.log(that.sourceEvents);
      }).catch((err) => {
        console.log(err)
      });
    },
    addRule() {
      this.objectRules.push({});
    },
    removeRule(index) {
      if (index !== 0) {
        this.objectRules.splice(index, 1)
      }
    }
  }
};
</script>
